#include "soundsystemfmod.h"
#include <QDebug>

void SoundSystemFMOD::create()
{
   mInstance = new SoundSystemFMOD();
}

SoundSystemFMOD::SoundSystemFMOD()
{
   mSystem = 0;
   FMOD_RESULT result;

   result = FMOD_System_Create(&mSystem);
   if (result != FMOD_OK)
      qDebug() << "FMOD ERROR: System_Create" << "error=" << result;

   result = FMOD_System_Init(mSystem, 32, FMOD_INIT_NORMAL, NULL);
   if (result != FMOD_OK)
      qDebug() << "FMOD ERROR: FMOD_System_Init" << "error=" << result;

   createSounds();

   qDebug() << "SoundSystemFMOD::initialized!";
}

SoundSystemFMOD::~SoundSystemFMOD()
{
   FMOD_System_Close(mSystem);
   FMOD_System_Release(mSystem);
   qDebug() << "~SoundSystemFMOD";
}

void SoundSystemFMOD::createSounds()
{
   mSounds[SFX_TOWER_BEAM_FIRE] = loadSound("./res/sfx/beamfire.wav");
   mSounds[SFX_UNIT_DEATH] = loadSound("./res/sfx/die5.wav");
}

void SoundSystemFMOD::releaseSounds()
{
   FMOD_Sound_Release(mSounds.value(SFX_TOWER_BEAM_FIRE));
   mSounds.remove(SFX_TOWER_BEAM_FIRE);
   FMOD_Sound_Release(mSounds.value(SFX_UNIT_DEATH));
   mSounds.remove(SFX_UNIT_DEATH);
}

bool SoundSystemFMOD::playSound(const SFX_TYPE sfx)
{
   FMOD_CHANNEL *channel = 0;
   FMOD_RESULT result = FMOD_OK;

   if (mSystem)
   {
      if (mSounds.contains(sfx))
      {
         result = FMOD_System_PlaySound(mSystem, FMOD_CHANNEL_FREE, mSounds.value(sfx), 0, &channel);
         if (result != FMOD_OK)
            qDebug() << "FMOD ERROR: FMOD_System_PlaySound" << "error=" << result;
      }
      FMOD_System_Update(mSystem); // refreshes open channels
   }
   else
   {
      qDebug() << "ERROR: SoundSystemFMOD::playSound: no instance.";
      return false;
   }

   return (result == FMOD_OK);
}

FMOD_SOUND* SoundSystemFMOD::loadSound(const QString &filename)
{
   FMOD_RESULT result;
   FMOD_SOUND *sound = 0;
   result = FMOD_System_CreateSound(mSystem, filename.toStdString().c_str(), FMOD_SOFTWARE, 0, &sound);
   if (result != FMOD_OK)
      qDebug() << "FMOD ERROR: FMOD_System_CreateSound" << filename << "error=" << result;
   return sound;
}

bool SoundSystemFMOD::mute(bool value)
{
   FMOD_CHANNELGROUP *cg;
   FMOD_RESULT result;
   result = FMOD_System_GetMasterChannelGroup(mSystem, &cg);
   if (result != FMOD_OK)
      return false;
   result = FMOD_ChannelGroup_SetVolume(cg, ((value) ? 0 : 1));
   if (result != FMOD_OK)
      return false;
   return true;
}
